import React from 'react';
import style from './style.objective-create';
import { Button, List, IconButton, Select, Input, LabelInput, InlineButtonInput } from 'sq-ui';
import { success, info, Modal, DateSelect, Checkbox, MulSelect, SelectList } from '../../ui-components';
import util from '../../util';
import cx from 'classnames';
import { checkCurrentAmount } from './Objective';
import { GuideInfo, NextGuide,GuideBox } from '../guide/Guide';

export default
class ObjectiveCreate extends React.Component {
  constructor(props) {
    super(props);
    this.selectedPeriod = props.params.periodId;
    const {
      createObjective,
      editObjective,
      editKeyResult,
      createKeyResult,
      objective,
      objectiveId,
      keyResult,
      objectiveType, // 创建目标的类型
      okr,
    } = props;

    const {
      content='',
      priority=0,
      progressMetricType=1,
      startingAmount='0',
      goalAmount='100',
      currentAmount='0',
      unit='%',
      directorList=[],
    } = (editObjective? (objective || {}): editKeyResult? (keyResult || {}): {});

    let unitType = 0;
    if (progressMetricType) {
      unitType = progressMetricType - 1;
    }

    // 创建/编辑关键结果增加AMB，原因，计划，注释字段
    let departmentOtherGoal = {};
    if( createKeyResult || editKeyResult ){
      departmentOtherGoal = {
        why: "",
        howMeasure: "",
        actionPlan: "",
        notes: ""
      }
    }

    this.init = {
      content,
      priority,
      progressMetricType,
      startingAmount,
      goalAmount,
      currentAmount,
      unit,
      directorList,
      deleteObjective: false,
      deleteKeyResult: false,
      deleteItem: false,
    };

    // 创建目标
    let selectPreObjective = null;
    let selectCopyLead = null;
    if (createObjective) {
      let addPersonalObjective = {}, copyGoalOrResult = null;
      if(objectiveType === "2"){ // 如果为部门目标
        addPersonalObjective = { addPersonalObjective: 0 };
      }
      if(objectiveType === "3"){ // 如果为个人目标
        // 复制上级的目标/结果作为个人目标，copyGoalOrResult: 是否复制；
        copyGoalOrResult = { copyGoalOrResult: 0 };
        // 复制的上级目标/结果
        selectCopyLead = { copyLeadKeyWord: "" };
      }
      selectPreObjective = { preKeyword: "" };
      this.objectiveInit = {
        objectivePeriodId: props.params.periodId,
        isAutoCalc: 1,
        isPrivate: 0,
        deadline: '',
        challenge: 1, // 挑战难度等级
        regularRemindType: 1,
        isRenderPreObjective: false, // 是否渲染上一周期目标列表数据
        isRenderPreKeyResult: false, // 是否渲染上一周期结果列表数据
        isRenderCopyLead: false, // 是否渲染上级目标结果列表数据
        ...addPersonalObjective, // 创建部门目标时是否同时创建个人目标
        ...copyGoalOrResult, // 复制上级的目标结果作为自己的目标
        ...selectCopyLead, // 上级目标结果
        ...this.init,
        directorList: props.location.query.type == 3 ? [
          {
            coreUserProfileVO: this.props.app.profile,
          }
        ] : [],
      };
    }
    
    // 编辑目标
    if (editObjective) {
      const { regularRemindType=1, challenge=1, challengeDesc, objectiveId, isAutoCalc, isPrivate, 
        deadline, why, actionPlan, howMeasure, notes } = objective;
      this.objectiveInit = {
        objectivePeriodId: props.params.periodId,
        objectiveId,
        isAutoCalc,
        isPrivate,
        deadline,
        regularRemindType,
        challenge: challenge ? challenge : 1, // 挑战难度等级
        challengeDesc,
        ...this.init,
      };
    }

    // 编辑关键结果
    if (editKeyResult) {
      const { deadline, objectiveId, keyResultId, why, actionPlan, 
        howMeasure, notes } = keyResult;
      this.keyResultInit = {
        objectiveId,
        keyResultId,
        deadline,
        why,
        actionPlan,
        howMeasure,
        notes,
        ...this.init,
      };
    }
    
    // 创建关键结果
    let selectPreKeyResult = null;
    if (createKeyResult) {
      selectPreKeyResult = { preKeyWordResult: "" };
      this.keyResultInit = {
        deadline: '',
        objectiveId: props.objectiveId,
        ...this.init,
        ...departmentOtherGoal,
        directorList: props.location.query.type == 3 ? [
          {
            coreUserProfileVO: this.props.app.profile,
          }
        ] : [],
      };
    }

    this.state = {
      unitType,
      // 搜索
      keyword: '',
      isRenderObjective: true,
      ...selectPreObjective, // 上一周期的目标内容及搜索关键字
      ...selectPreKeyResult, // 上一周期的结果内容及搜索关键字
      selectObjective: (objective || {}).parentObjectiveName? { objectiveId: objective.parentObjectiveId, content: objective.parentObjectiveName } : null,
      showTip: false,
      field: (createObjective || editObjective) ? this.objectiveInit: this.keyResultInit,
      dialogH: "auto",
    };
  }

  static contextTypes = {
    router: React.PropTypes.object
  }

  componentWillUnmount() {
    this.unmount = true;
  }
  showTip(hide) {
    if (hide) {
      this.setState({ showTip: false, });
      return;
    }
    const { showTip } = this.state;
    if (showTip) return;
    this.setState({ showTip: true, });
  }

  // 选择并设置周期，
  handlePeriodChange(value) {
    this.selectedPeriod = value;
  }

  resetSearch(type) { // 重置选择
    let target = "selectObjective"; // 清空选择的上级目标
    if(type === "preObjective"){ // 重置选择的上一周期目标
      target = "selectPreObjective";
    }else if(type === "preKeyResult"){ // 重置选择的上一周期结果
      target = "selectPreKeyResult";
    }else if(type === "copyLead"){ // 重置选择的上级目标结果
      target = "selectCopyLead";
    }
    this.setState({ [target]: null, });
  }

  clearSearch(type) { // 关闭下拉选择
    let method = 'resetObjectiveSearch'; // 清空选择上级目标的结果重新选择
    if(type === 'preObjective'){ // 清空选择的上一周期目标重新选择
      method = 'resetPreObjective';
    }else if(type === 'preKeyResult'){ // 清空选择的上一周期结果重新选择
      method = 'resetPreObjective';
    }else if(type === 'copyLead'){ // 清空选择的复制的目标结果重新选择
      method = 'resetCopyLead';
    }
    this.props.actions[method]();
    this.setState({
      isRenderObjective: false,
      isRenderPreObjective: false,
      isRenderPreKeyResult: false,
      isRenderCopyLead: false
    });
  }

  // 查询上级目标
  searchObjective(e) {
    let { value } = e.target;
    value = value.trim();
    this.setState({
      keyword: value,
      isRenderObjective: true,
      isRenderPreObjective: false, // setState后props会重新获取，防止重新渲染上一周期目标数据
      isRenderPreKeyResult: false,
      isRenderCopyLead: false
    });
    const { objective={}, actions } = this.props;
    const { objectiveId } = objective;
    // 更新
    if (objectiveId) {
      actions.searchObjective({ keyword: value, objectiveId });
    } else {
      actions.searchObjective({ keyword: value });
    }
  }
  // 点击选择上级目标
  handleSelectSearchObjective(objective) {
    this.setState({
      selectObjective: objective,
      keyword: '',
    }, () => {this.clearSearch()});
  }
  // 上级目标列表
  renderSearchObjective() {
    const { okr } = this.props;
    const { search } = okr;
    if (util.isNull(search)) return null;
    return <ul style={{position: "absolute", top: "100%"}} className={style["list-box"]}>
    {
      search.map(item => {
        return(
          <li key={item.objectiveId} 
              onMouseDown={e => this.handleSelectSearchObjective(item)}>
            <p style={{ fontSize: '13px' }}>{item.content}</p>
            <p style={{ color: '#8fa6bf', fontSize: '12px' }}>{item.objectivePeriodOwnerName} > {item.objectivePeriodName}</p>
          </li>
        )
      })
    }
    </ul>
  }

  searchPreObjective(e){ // 查询上一周期的目标
    this.setState({
      preKeyword: "",
      isRenderObjective: false,
      isRenderPreObjective: true, // 允许渲染上一周期目标数据，阻止渲染上级目标数据
      isRenderPreKeyResult: false,
      isRenderCopyLead: false
    });
    this.props.actions.fetchPreObjective({periodId: this.selectedPeriod});
  }
  // 点击选择上一周期目标
  handleSelectPreSearchObjective(objective) {
    let result = {};
    let arr = ['comment', 'createdTime', 'createdUserId', 'editable', 'hasParent', 'hasSubordinate',
      'keyResultList', 'lastModifiedTime', 'lastModifiedUserId', 'lastModifiedUserProfile',
      'objectiveId', 'objectivePeriodId', 'objectivePeriodName', 'objectivePeriodOwnerJobTitleName',
      'objectivePeriodOwnerName', 'orderIndex', 'orgId', 'ownerId', 'parentObjectiveId',
      'parentObjectiveName', 'progress', 'progressMetricType', 'startingAmount', 'type', 
      "directorList"];
    for(let key in objective){
      if(arr.indexOf(key) === -1){
        result[key] = objective[key];
      }
    }
    this.setState({
      selectPreObjective: objective,
      preKeyword: '',
      field: {
        ...this.state.field,
        ...result
      }
    }, () => {this.clearSearch("preObjective")});
  }
  // 上周期目标列表
  renderSearchPreObjective() {
    const { okr } = this.props;
    const { objectiveVOList } = okr;
    if (objectiveVOList.length === 0) return null;
    let result = [];
    objectiveVOList.forEach(item => { // 筛选未完成的
      if((+item.progress * 100) < 100) result.push(item);
    });
    return <ul style={{position: "absolute", top: "100%"}} className={style["list-box"]}>
    {
      result.map(item => {
        return(
          <li key={item.objectiveId}
              onMouseDown={e => this.handleSelectPreSearchObjective(item)}>
            <p style={{ fontSize: '13px' }}>{item.content}</p>
          </li>
        )
      })
    }
    </ul>
  }

  searchPreKeyResult(e){ // 查询上一周期的结果
    this.setState({
      preKeyWordResult: "",
      isRenderObjective: false,
      isRenderPreObjective: false,
      isRenderPreKeyResult: true, // 允许渲染上一周期目标数据，阻止渲染上级目标数据
      isRenderCopyLead: false,
    });
    this.props.actions.fetchPreObjective({periodId: this.selectedPeriod});
  }
  handleSelectPreSearchKeyResult(objective) { // 点击选择上一周期结果
    let result = {};
    let arr = ["comment", "keyResultId", "objectiveId", "orgId", "directorList", "progress", "unit"]
    for(let key in objective){
      if(arr.indexOf(key) === -1){
        result[key] = objective[key];
      }
    }
    this.setState({
      selectPreKeyResult: objective,
      preKeyWordResult: '',
      field: {
        ...this.state.field,
        ...result
      }
    }, () => {this.clearSearch("preKeyResult")});
  }
  renderPreKeyResult() { // 上周期结果列表
    const { okr } = this.props;
    const { objectiveVOList } = okr;
    if (objectiveVOList.length === 0) return null;
    return <ul style={{position: "absolute", top: "100%"}} className={style['pre-objective-box']}>
    {
      objectiveVOList.map(item => {
        return(
          <li key={item.objectiveId} className={style['pre-objective-item']}>
            <p>{item.content}</p>
            <ul className={style['pre-keyResult-box']}>
            {
              item.keyResultList ? 
                item.keyResultList.map(v => { // 筛选未完成的
                  return ( +v.progress * 100) < 100 ? <li onMouseDown={e => this.handleSelectPreSearchKeyResult(v)} 
                    className={style['pre-keyResult-item']}
                    key={v.keyResultId}>{v.content}</li> : null
                }) : null
            }
            </ul>
          </li>
        )
      })
    }
    </ul>
  }

  searchCopyLead(e){ // 复制上周期的目标结果
    this.setState({
      copyLeadKeyWord: "",
      isRenderObjective: false,
      isRenderPreObjective: false,
      isRenderPreKeyResult: false,
      isRenderCopyLead: true, // 允许渲染上级目标结果，阻止渲染上级目标数据
    });
    this.props.actions.fetchCopyLead(); 
  }
  // 点击选择上级目标结果
  handleSelectCopyLead(objective) {
    let result = {
      'content': objective['content'], // 内容
      'isAutoCalc': objective['isAutoCalc'], // 衡量方式
      'startingAmount': objective['startingAmount'], // 衡量开始值
      'goalAmount': objective['goalAmount'], // 衡量目标值
      'currentAmount': objective['currentAmount'], // 当前进度
      'priority': objective['priority'], // 优先级
    };
    this.setState({
      selectCopyLead: objective,
      copyLeadKeyWord: '',
      field: {
        ...this.state.field,
        ...result
      }
    }, () => {this.clearSearch("copyLead")});
  }
  // 上级目标结果
  renderCopyLead() {
    const { okr } = this.props;
    const { copyLeadList } = okr;
    if (copyLeadList.length === 0) return null;
    return <ul style={{position: "absolute", top: "100%"}} className={style['pre-objective-box']}>
    {
      copyLeadList.map(item => {
        return(
          <li key={item.objectiveId} className={style['pre-objective-item']+" "+style['can-select']}>
            <p onMouseDown={e => this.handleSelectCopyLead(item)}>{item.content}</p>
            <ul className={style['pre-keyResult-box']}>
            {
              item.keyResultList ? 
                item.keyResultList.map(v => { // 筛选未完成的
                  return <li onMouseDown={e => this.handleSelectCopyLead(v)} className={style['pre-keyResult-item']} key={v.keyResultId}>{v.content}</li>
                }) : null
            }
            </ul>
          </li>
        )
      })
    }
    </ul>
  }

  updateCurrentAmount(e) {
    let { value } = e.target;
    if (this.state.field.progressMetricType == 1) {
      value = checkCurrentAmount(value);
      if (value === false) return;
    }
    this.updateField('currentAmount', value);
  }
  updateStartingAmount(e) {
    this.setState({
      field: {
        ...this.state.field,
        startingAmount: e.target.value,
        currentAmount: e.target.value,
      }
    })
  }
  handleSelectDiector(obj) {
    this.updateField('directorList', obj.map(v => {
      return { coreUserProfileVO: v }
    }));
  }

  changeUnitType(unitType) {
    const unit = unitType == 0 ? '%': unitType == 1? '元': '';
    const progressMetricType = unitType+1
    const goalAmount = unitType == 0? '100': '0';
    this.setState({
      unitType, 
      field: { ...this.state.field, unit, progressMetricType, goalAmount, },
    });

    if (unitType == 1) {
      this.refs.startCount.focus();
    } else if (unitType == 2) {  }  
  }

  updateField(name, value) {
    // 判断是否同时添加个人目标或者选取与上级项目的目标结果
    if(name === "addPersonalObjective" || name === "copyGoalOrResult"){
      value = (value === false || value === "false") ? 0 : 1;
    }
    this.setState({
      field: {
        ...this.state.field,
        [name]: (name === 'content') ? value : typeof value === 'string'? value.trim() : value
      }
    })
  }

  requestDeleteObjective() {
    this.setState({
      deleteItem: true,
      deleteObjective: true
    })
  }

  requestDeleteKeyResult() {
    this.setState({
      deleteItem: true,
      deleteKeyResult: true,
    });
  }

  cancelDeleteItem() {
    this.setState({
      deleteItem: false,
    }, () => {
      setTimeout(() => {
        if (this.unmount) return;
        this.setState({
          deleteObjective: false,
          deleteKeyResult: false,
          kr: null
        });
      }, 200)
    })
  }

  deleteObjective() {
    info('删除中...');
    this.props.actions.deleteObjective(this.props.objective.objectiveId, () => {
      if (this.props.editObjectiveDetail) {
        const { query } = this.props.location;
        this.context.router.replace({
          query,
          pathname: `/okr/${this.props.objectivePeriodId}/objectives`,
        });
      } else {
        this.props.fetchObjective(null, true);
      }
      success('删除成功!');
    });
    this.props.onRequestClose();
    this.cancelDeleteItem();
  }

  deleteKeyResult() {
    info('删除中...');
    this.props.actions.deleteKeyResult(this.props.keyResult.keyResultId, () => {
      success('删除成功!');
      if (this.props.editObjectiveDetail) {
        this.props.refreshKeyResult();
      } else {
        this.props.fetchObjective();
      }
    });
    this.props.onRequestClose();
    this.cancelDeleteItem();
  }

  componentDidMount(){
    let h = document.body.clientHeight;
    this.setState({
      dialogH: (h - 46 - 60 - 30) + "px"
    });
  }

  render() {
    const { createObjective, editObjective, createKeyResult, editKeyResult, objectiveType } = this.props;
    const { objective } = this.props.okr;
    const { objectiveDeletable} = objective;
    const isObjective = (createObjective || editObjective); // 获取是否为目标的表达式结果
    const itemName = isObjective ? 'O目标': 'KR关键结果';
    const { type } = this.props.location.query;
    const { period } = this.props.okr;
    const { objectivePeriods } = period;
    return (
      <div className={style.root} style={{height: this.state.dialogH, overflowY: "auto", overflowX: "hidden"}}>
        {
          createObjective ?
          <div className={style['input-two']} style={{ position: 'relative' }} >
            <label style={{minWidth: "128px"}}>是否延续上周期目标</label>
            <div style={{ width: '450px', position: 'relative' }}>
              <Select id="objectivePeriodId" 
                className={style['priority-select']} 
                style={{ width: '185px' }}
                value={this.props.params.periodId} 
                onChange={::this.handlePeriodChange} 
                list={objectivePeriods}
                item={item => <li key={item.objectivePeriodId} data-value={item.objectivePeriodId}>{item.name}</li>}
              />
            </div>
            {
              (this.props.app.naviStep == 3 && this.props.app.guide == 3) ? 
                <GuideInfo lineWidth="45" info={[ '选择上一周期' ]}/> : null
            }
          </div>: null
        }
        {
          createObjective ?
          <div className={style['input-two']} style={{ position: 'relative' }}>
            <label style={{minWidth: "128px"}}>选择上周期目标</label>
            <div style={{ width: '100%', position: 'relative' }}>
              {
                this.state.selectPreObjective ? 
                  <div className={style['selected-objective']}>
                    <span>{ this.state.selectPreObjective.content }</span>
                    <IconButton icon="close" onClick={this.resetSearch.bind(this, "preObjective")}/>
                  </div> : 
                  <Input value={this.state.preKeyword} onChange={::this.searchPreObjective}
                    onBlur={this.clearSearch.bind(this, "preObjective")} onFocus={::this.searchPreObjective}/>
              }
              { this.state.isRenderPreObjective ? this.renderSearchPreObjective() : null }
            </div>
            {
              (this.props.app.naviStep == 3 && this.props.app.guide == 3) ? 
                <GuideInfo lineWidth="45" info={[ '选择上一个周期未完成的目标，这将快速建立一个目标' ]} /> : null
            }
          </div>: null
        }
        <div style={{position: 'relative'}}>
          <LabelInput
            autoFocus
            vertical
            className={style['input-one']}
            value={this.state.field.content}
            onChange={e => this.updateField('content', e.target.value)}
            onKeyDown={e => {
              if (e.which === 13) {
                this.props.submit();
              }
            }}
            label={itemName}
            placeholder={`输入${itemName}名称`}
          />
          {
            ((this.props.app.naviStep == 3 || this.props.app.naviStep == 4) && this.props.app.guide == 3) ? (
              <GuideInfo
                lineWidth="44"
                info={[
                  this.props.app.naviStep == 3 ? '思考你的工作的价值，设定有挑战性的目标！': '撰写关键结果，以有效衡量目标达成情况',
                ]}
              />
            ) : null
          }
        </div>
        {
          createKeyResult || editKeyResult ? 
          <div style={{position: 'relative'}}>
            <LabelInput
              vertical
              value={this.state.field.why}
              onChange={e => this.updateField('why', e.target.value)}
              className={style['input-one']}
              label='如何衡量？（定量/定性）'
              placeholder={`输入目标的衡量标准`}
            />
          </div>
          : null
        }
        {
          createKeyResult || editKeyResult ? 
          <div style={{position: 'relative'}}>
            <LabelInput
              vertical
              value={this.state.field.howMeasure}
              onChange={e => this.updateField('howMeasure', e.target.value)}
              className={style['input-one']}
              label={`创建原因${objectiveType === "3" ? 
                "（关键结果对于战略、业务和个人发展的影响）" : "（关键结果对于战略、业务的影响）"}`}
              placeholder={`输入目标创建原因`}
            />
          </div>
          : null
        }
        {
          createKeyResult || editKeyResult ? 
          <div style={{position: 'relative'}}>
            <LabelInput
              vertical
              value={this.state.field.actionPlan}
              onChange={e => this.updateField('actionPlan', e.target.value)}
              className={style['input-one']}
              label='关键行动'
              placeholder={`输入你的关键行动`}
            />
          </div>
          : null
        }
        {
          createKeyResult || editKeyResult ? 
          <div style={{position: 'relative'}}>
            <LabelInput
              vertical
              value={this.state.field.notes}
              onChange={e => this.updateField('notes', e.target.value)}
              className={style['input-one']}
              label='注释'
              placeholder={`输入目标的注释`}
            />
          </div>
          : null
        }
        {
          (createObjective && objectiveType === '2') ? 
          <div className={style['input-one']}>
            <div style={{ position: 'relative' }} className={style.label}>
              <label>个人目标建立</label>
              <Checkbox
                active={this.state.field.addPersonalObjective === 1}
                className={style['progress-metric-type']}
                onClick={() => this.updateField('addPersonalObjective', !this.state.field.addPersonalObjective)}
                label="将建立的部门目标同时作为个人目标"
              />
              {
                (this.props.app.naviStep == 3 && this.props.app.guide == 3) ? (
                  <GuideInfo styles={{ left: '222px', bottom: '9px', }} lineWidth="403"
                    info={[ '将建立的部门目标同时作为个人目标' ]} />
                ) : null
              }
            </div>
          </div>: null
        }
        {
          (createObjective && objectiveType === '3') ? 
          <div className={style['input-one']}>
            <div style={{ position: 'relative' }} className={style.label}>
              <label>复制上级目标结果</label>
              <Checkbox
                active={this.state.field.copyGoalOrResult === 1}
                className={style['progress-metric-type']}
                onClick={() => this.updateField('copyGoalOrResult', !this.state.field.copyGoalOrResult)}
                label="从上级建立的目标/结果中选取作为个人目标"
              />
              {
                (this.props.app.naviStep == 3 && this.props.app.guide == 3) ? (
                  <GuideInfo styles={{ left: '222px', bottom: '9px', }} lineWidth="403"
                    info={[ '从上级建立的目标/结果中选取作为个人目标' ]} />
                ) : null
              }
            </div>
          </div>: null
        }
        <div className={style['input-one']}>
          <div style={{ position: 'relative' }} className={style.label}>
            <label>进度衡量方式</label>
            {
              isObjective ?
              <Checkbox
                className={style['progress-metric-type']}
                label="根据关键结果自动计算"
                active={this.state.field.isAutoCalc}
                onClick={() => {
                  if (this.state.field.isAutoCalc == 0) {
                    this.showTip(true);
                  } else {
                    this.showTip();
                  }
                  this.updateField('isAutoCalc', 1-this.state.field.isAutoCalc)
                }}
              />: null
            }
            {
              ((this.props.app.naviStep == 3 || this.props.app.naviStep == 4) && this.props.app.guide == 3) ? (
                <GuideInfo
                  styles={{ left: this.props.app.naviStep == 3 ?'258px': '98px',  bottom: '9px',}}
                  lineWidth={this.props.app.naviStep == 3 ? "367" : "526"}
                  info={[
                    this.props.app.naviStep == 3 ?'选择衡量目标达成情况的方式，也可以过后':'根据业务需要，灵活设定不同的衡量方式，',
                    this.props.app.naviStep == 3 ?'创建关键结果，根据关键结果自动计算':'系统将自动计算进度',
                  ]}
                />
              ) : null
            }
          </div>
          {
            !this.state.field.isAutoCalc ?
            <div>
              <InlineButtonInput
                className={style['inline-button-input']}
                buttonActive={this.state.unitType}
                buttonActions={[ '百分比', '金额', '自定义' ].map((v, i) => ({
                  label: v,
                  onClick: () => {
                    if (this.state.unitType == i) return;
                    if (this.state.field.isAutoCalc == 0) {
                      this.showTip();
                    }
                    this.changeUnitType(i);
                  }
                }))}
                value={this.state.field.unit}
                placeholder="填写单位"
                disabled={this.state.unitType != 2}
                onChange={e => {
                  this.updateField('unit', e.target.value)
                  if (this.state.field.isAutoCalc == 0) {
                    this.showTip();
                  }
                }}
                autoFocus={this.state.unitType == 2}
              />
              <div className={style['label-input-group']}>
                <div>
                  <label>开始值</label>
                  <input autoFocus ref="startCount" value={this.state.field.startingAmount}
                    disabled={this.state.unitType == 0}
                    onChange={e => {
                      if(createKeyResult)
                        this.updateStartingAmount(e);
                      else
                        this.updateField('startingAmount', e.target.value)
                      if (this.state.field.isAutoCalc == 0) {
                        this.showTip();
                      }
                    }}
                  />
                </div>
                <div style={{ position: 'relative' }}>
                  <label>目标值</label>
                  <input value={this.state.field.goalAmount} disabled={this.state.unitType == 0}
                    onChange={e => {
                      this.updateField('goalAmount', e.target.value);
                      if (this.state.field.isAutoCalc == 0) {
                        this.showTip();
                      }
                    }}
                  />
                </div>
              </div>
            </div>: null
          }
        </div>
        {
          (this.state.showTip && editObjective) || editKeyResult ? (
            <p style={{ color: '#777', backgroundColor: '#FFF7E6', border: '1px solid #FFEECC',
              padding: '6px 10px', fontSize: '12px', margin: '30px 0 15px 0',
            }}>衡量方式或开始值/目标值已发生变化，如果当前值需要跟随变化，请在下方修改：</p>
          ) : null
        }
        {
          createKeyResult ?
          <div className={style['input-two']} style={{ position: 'relative' }} >
            <label>选择上周期结果</label>
            <div style={{ width: '450px', position: 'relative' }}>
              {
                this.state.selectPreKeyResult? 
                  <div className={style['selected-objective']}>
                    <span>{ this.state.selectPreKeyResult.content }</span>
                    <IconButton icon="close" onClick={this.resetSearch.bind(this, "preKeyResult")} />
                  </div> : 
                  <Input value={this.state.preKeywordResult} onChange={::this.searchPreKeyResult}
                    onBlur={this.clearSearch.bind(this, "preKeyResult")} onFocus={::this.searchPreKeyResult}/>
              }
              { this.state.isRenderPreKeyResult ? this.renderPreKeyResult() : null }
            </div>
            {
              (this.props.app.naviStep == 3 && this.props.app.guide == 3) ? 
                <GuideInfo lineWidth="45" info={[ '选择上一周期未完成结果，这将快速简历一个完整的结果' ]}/> : null
            }
          </div>: null
        }
        {
          (!this.state.field.isAutoCalc) ?
          <div className={style['input-two']} >
            <label>当前进度</label>
            <div style={{ marginRight: '5px' }}>
              <Input onChange={::this.updateCurrentAmount} value={this.state.field.currentAmount}/>
            </div>
            {
              this.state.field.progressMetricType == 1? <span>%</span>
              : <span style={{ letterSpace: '' }}>/{this.state.field.goalAmount}{this.state.field.unit}</span>
            }
          </div>: null
        }
        {
          this.state.field.copyGoalOrResult === 1 ? 
          <div className={style['input-two']+' '+style['input-search']} style={{ position: 'relative' }}>
            <label>复制上级目标结果</label>
            <div style={{ width: '450px', position: 'relative' }}>
              {
                this.state.selectCopyLead ? 
                  <div className={style['selected-objective']}>
                    <span>{ this.state.selectCopyLead.content }</span>
                    <IconButton icon="close" onClick={this.resetSearch.bind(this, "copyLead")} />
                  </div> : 
                  <Input value={this.state.copyLeadKeyWord} onChange={::this.searchCopyLead}
                    onBlur={this.clearSearch.bind(this, "copyLead")} onFocus={::this.searchCopyLead}/>
              }
              { this.state.isRenderCopyLead ? this.renderCopyLead() : null }
            </div> 
          </div> : null
        }
        {
          ((createObjective || editObjective) && objectiveType !== "1") ?
          <div className={style['input-two']} style={{ position: 'relative' }} >
            <label>上级目标（选填）</label>
            <div style={{ width: '450px', position: 'relative' }}>
              {
                this.state.selectObjective? 
                  <div className={style['selected-objective']}>
                    <span>{ this.state.selectObjective.content }</span>
                    <IconButton icon="close" onClick={this.resetSearch.bind(this)} />
                  </div> : 
                  <Input value={this.state.keyword} onChange={::this.searchObjective}
                    onBlur={::this.clearSearch} onFocus={::this.searchObjective}/>
              }
              { this.state.isRenderObjective ? this.renderSearchObjective() : null }
            </div>
            {
              (this.props.app.naviStep == 3 && this.props.app.guide == 3) ? 
                <GuideInfo lineWidth="45" info={[ '选择上级目标，这将形成一个完整的目标树' ]}/> : null
            }
          </div>: null
        }
        <div style={{ position: 'relative' }} className={style['input-two']}>
          <label>负责人（选填）</label>
          <MulSelect placeholder="搜索负责人.." width={451}
            value={this.state.field.directorList.map(v => v.coreUserProfileVO)}
            fetch={value => {
              if (value)
                this.props.actions.fetchAtList(value);
              else
                this.props.actions.clearAtList();
            }}
            getItemAttrs={(item) => {
              return { label: item.fullName, img: item.avatarUrl, }
            }}
            onSelect={::this.handleSelectDiector}
            options={this.props.app.atList}
          />
          {
            ((this.props.app.naviStep == 3 || this.props.app.naviStep == 4) && this.props.app.guide == 3) ? (
              <GuideInfo lineWidth="45" info={[ this.props.app.naviStep == 3 ?'他们是目标的实现者！': '填写关键结果负责人' ]} />
            ) : null
          }
        </div>
        <div style={{ position: 'relative' }} className={style['input-two']}>
          <label>优先级</label>
          <Select
            className={style['priority-select']}
            style={{ width: '85px' }}
            value={this.state.field.priority+''}
            onChange={value => this.updateField('priority', value)}
            list={[ '极高', '高', '中', '低', ]}
            activeItem={(v, i, active) => (
              <li style={{ paddingLeft: active? '35px': '25px', }}
                className={cx(style.priority, style[`priority-${i}`], { [style.active]: active })} key={i}
                data-value={i}>
                  <span>{v}</span>
              </li>
            )}
            item={(v, i, active) => (
              <li className={cx(style.priority, style[`priority-${i}`], { [style.active]: active })} key={i}
                data-value={i} >
                <span>{v}</span>
              </li>
            )}
          />
          {
            ((this.props.app.naviStep == 3 || this.props.app.naviStep == 4) && this.props.app.guide == 3) ? (
              <GuideInfo styles={{ left: '211px', bottom: '12px', }} lineWidth="414"
                info={[ '要事先做，设定优先级，默认为「极高」' ]} />
            ) : null
          }
        </div>
        {
          (createObjective || editObjective) ? 
          <div className={style['input-two']} style={{ position: 'relative' }}>
            <label>挑战度</label>
            <Select style={{width: '96px'}} value={`${this.state.field.challenge - 1}`}
              onChange={v => this.updateField('challenge', +v + 1)}
              list={[ '1', '2', '3', '4', ]}
              item={(v, i) => (
                <li data-value={i} key={i}>
                  <span>{v}</span>
                </li>
              )}
            />
            {
              (this.props.app.naviStep == 3 && this.props.app.guide == 3) ? 
                <GuideInfo styles={{ left: '222px', bottom: '12px',}}
                  lineWidth="403" info={[ '可以在这里选择自己挑战的挑战度~' ]} />
               : null
            }
          </div> : null
        }
        {
          (createObjective || editObjective) ? 
          <div style={{position: 'relative'}}>
            <LabelInput
              vertical
              className={style['input-one']}
              value={this.state.field.challengeDesc}
              onChange={e => this.updateField('challengeDesc', e.target.value)}
              onKeyDown={e => {
                if (e.which === 13) {
                  this.props.submit();
                }
              }}
              label={'挑战度说明'}
              placeholder={`输入挑战度说明`}
            />
            {
                (this.props.app.naviStep == 3 && this.props.app.guide == 3) ? 
                  <GuideInfo styles={{ left: '222px', bottom: '12px',}}
                    lineWidth="403" info={[ '可以在这里选择自己挑战的挑战度~' ]} />
                : null
            }
          </div> : null
        }
        <div className={style['input-two']} style={{ position: 'relative' }}>
          <label>截止日（选填）</label>
          <DateSelect
            time={!util.isNull(this.state.field.deadline)? util.time(this.state.field.deadline, '-'): ''}
            onChange={v => this.updateField('deadline', v)}
          />
          {
            ((this.props.app.naviStep == 3 || this.props.app.naviStep == 4) && this.props.app.guide == 3) ? (
              <GuideInfo styles={{ left: '430px', }} lineWidth="195" info={[ '设定截止日' ]} />
            ) : null
          }
        </div>
        {
          isObjective ? (
            <div className={style['input-two']} style={{ position: 'relative' }}>
              <label>定期提醒设置：</label>
              <Select style={{width: '96px'}} value={`${+this.state.field.regularRemindType-1}`}
                onChange={v => this.updateField('regularRemindType', +v + 1)}
                list={[ '不提醒', '每周提醒', '每两周提醒', '每月提醒', ]}
                item={(v, i) => (
                  <li data-value={i} key={i}>
                    <span>{v}</span>
                  </li>
                )}
              />
              {
                (this.props.app.naviStep == 3 && this.props.app.guide == 3) ? (
                  <GuideInfo styles={{ left: '222px', bottom: '12px', }} lineWidth="403"
                    info={[ '可以在这里提醒自己更新目标进展~']} />
                ) : null
              }
                </div>
              ) : null
            }
        {/* {
          isObjective ?
          <div style={{ position: 'relative' }} className={style['input-two']}>
            <label>权限</label>
            <Checkbox active={this.state.field.isPrivate == 1} className={style.check}
              onClick={() => this.updateField('isPrivate', 1-this.state.field.isPrivate)}
              label={type == 2? "仅目标/关键结果负责人、公司管理层和本团队成员可见": 
                type == 3 ? "仅目标/关键结果负责人、公司管理层和您自己可见": type == 4 ?
                "仅目标/关键结果负责人、公司管理层和本项目组成员可见" : "仅目标/关键结果负责人和公司管理层可见"}
            />
            {
              (this.props.app.naviStep == 3 && this.props.app.guide == 3) ? (
                <GuideInfo styles={{ left: '222px', bottom: '9px', }} lineWidth="403"
                  info={[ '如不宜公开请勾选' ]} />
              ) : null
            }
          </div>: null
        } */}
        {
          (this.props.editObjective || this.props.editKeyResult) && objectiveDeletable == true ? (
            <Button label="删除"
              onClick={() => {
                if (this.props.editObjective) {
                  this.requestDeleteObjective();
                } else {
                  this.requestDeleteKeyResult();
                }
              }}
              style={{ zIndex: '20', bottom: '15px', position: 'absolute',
                backgroundColor: 'rgb(255, 106, 106)', color: '#fff', width: '70px',
                height: '30px', fontSize: '12px' }}
            />) : null
        }
        {
          ((this.props.app.naviStep == 6 || this.props.app.naviStep == 3 || this.props.app.naviStep == 4) && this.props.app.guide == 3) ? (
            <NextGuide styles={{ left: '100%', marginLeft: '1px', marginTop: '23px' }}
              right large
              str={this.props.app.naviStep == 6 ? '修改后点击这里' : `点击确定，${this.props.app.naviStep == 3 ? '开始添加关键结果吧': '关键结果创建完成！'}`}
            />
          ) : null
        }
        {
          this.props.app.naviStep == 3 ? 
          <GuideBox title={'创建目标原则'}
            text={[ '1.如果是OKR方式的目标，需要有挑战性，60%-70%是sweet point',
              '2.能够体现团队/个人的工作价值和影响力',
              '3.不要写成工作任务！',]}
            styles={{ top: '10px', bottom: 'auto', left: 'auto', right: '105%', width: '200px', color: '#fff', }}
          />
          :null
        }
        {
          this.props.app.naviStep == 4 ? 
          <GuideBox title={'添加关键结果原则'}
            text={[ '1.如果是OKR方式的目标，需要有挑战性，60%-70%是sweet point',
              '2.S.M.A.R.T.',
              '3.不要写成工作任务！',]}
            styles={{ top: '10px', bottom: 'auto', left: 'auto', right: '105%', width: '200px', color: '#fff', }}
          />
          :null
        }
        <Modal
          active={this.state.deleteItem}
          onRequestClose={::this.cancelDeleteItem}
          title={this.state.deleteObjective? "删除目标": '删除关键结果'}
          actions={[ 'cancel', () => {
              if (this.state.deleteObjective) {
                this.deleteObjective();
              } else {
                this.deleteKeyResult();
              }
            }
          ]}
        >
          <p>确定{this.state.deleteObjective? "删除目标": '删除关键结果'}吗?</p>
        </Modal>
      </div>
    );
  }
}
